<template>
  <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <div class="head-container">
        <div class="table_title">计费项目</div>
        <div class="btn">
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 5px"
            @click="saveSingle"
            :disabled="!(this.tableList && this.tableList.length > 0)"
            >保存</el-button
          >
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 5px"
            @click="addSingle"
            >新增</el-button
          >
          <el-button type="primary" size="mini" @click="delSingle"
            >删除</el-button
          >
        </div>
      </div>
    </div>
    <el-table
      ref="table"
      v-loading="tableLoading"
      :data="tableList"
      row-key="hisItemId"
      @selection-change="selectionChangeHandler"
      :summary-method="getSummaries"
      show-summary
      :key="certKey"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="60px" prop="indexNumber">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        prop="costId"
        label="费用名称"
      >
        <template slot-scope="scope">
          <el-select
            v-model="tableList[scope.$index].costId"
            placeholder="请选择"
            clearable
            filterable
            :filter-method="filterDep"
            @change="changeDep(tableList[scope.$index].costId, scope.$index)"
            @blur="blurDep"
            @input="blurDep"
          >
            <el-option
              v-for="(item, index) in costList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价" />
      <el-table-column prop="chargeUnit" label="单位" />
      <el-table-column prop="bindNum" label="数量">
        <template slot-scope="scope">
          <el-input
            placeholder="请输入"
            v-model="tableList[scope.$index].bindNum"
            clearable
            type="number"
            min="1"
            @input="blurInput('bindNum', scope.$index)"
            @change="blurNum(tableList[scope.$index].bindNum, scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额" />
    </el-table>
  </el-card>
</template>

<script>
import moment from "moment";
import {
  getCost,
  searchCost,
  bindCost,
  unBind,
} from "@/api/treatmentProject/treatments";
export default {
  name: "singleItem",
  props: {
    activeRow: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      tableList: [],
      costList: [],
      tableLoading: false,
      selectedRowKeys: [],
      treatmentId: null,
      certKey: "",
    };
  },
  watch: {
    activeRow: function (val) {
      if (val) {
        this.treatmentId = val.treatmentId;
        this.getList();
      }
    },
  },
  mounted() {
    this.getCostList();
  },
  methods: {
    getList() {
      getCost({ treatmentId: this.treatmentId })
        .then((res) => {
          this.tableList = res.content;
        })
        .catch((res) => {
          this.$notify({
            title: res.msg,
            type: "error",
            duration: 2500,
          });
        });
    },
    getCostList(val = undefined) {
      searchCost({ costNameOrCode: val }).then((res) => {
        this.costList = res.content.map((item) => {
          return {
            ...item,
            label: item.costName,
            value: item.costId,
          };
        });
      });
    },
    filterDep(val) {
      this.getCostList(val);
    },
    changeDep(val, index) {
      // if (!val) this.getCostList();
      this.getCostList();
      let obj = this.costList.find((cost) => {
        return cost.value == val;
      });
      this.tableList.forEach((element, elIndex) => {
        Object.assign(element, {
          unitPrice: val
            ? index == elIndex
              ? obj
                ? obj.unitPrice
                : undefined
              : element.unitPrice
            : elIndex == index
            ? undefined
            : element.unitPrice,
          chargeUnit: val
            ? index == elIndex
              ? obj
                ? obj.chargeUnit
                : undefined
              : element.chargeUnit
            : elIndex == index
            ? undefined
            : element.chargeUnit,
          amount: val
            ? elIndex == index
              ? element.bindNum
                ? element.bindNum * obj.unitPrice || 0
                : element.unitPrice
              : element.amount
            : elIndex == index
            ? 0
            : element.amount,
        });
      });
    },
    blurDep() {
      this.getCostList();
    },
    blurInput(label, index) {
      this.tableList[index][label] = this.tableList[index][label].replace(
        /^(0+)|[^\d]+/g,
        ""
      );
    },
    blurNum(val, index) {
      this.certKey = !this.certKey;
      this.tableList.forEach((element, elIndex) => {
        Object.assign(element, {
          amount:
            elIndex == index ? (element.unitPrice || 0) * val : element.amount,
        });
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 5) {
          sums[index] = "合计（元）";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[6] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    isRepeat(arr) {
      var hash = {};
      for (var i in arr) {
        if (hash[arr[i]]) return true;
        hash[arr[i]] = true;
      }
      return false;
    },
    //保存
    saveSingle() {
      let isReturn = this.isRepeat(
        this.tableList.map((item) => {
          return item.costId;
        })
      );
      if (isReturn) {
        this.$notify({
          title: "请勿重复添加费用名称",
          type: "warning",
          duration: 2500,
        });
      } else {
        let float = this.tableList.every((item) => {
          if (!item.costId) {
            this.$notify({
              title: "费用名称不能为空",
              type: "warning",
              duration: 2500,
            });
          } else if (!item.bindNum) {
            this.$notify({
              title: "数量不能为空",
              type: "warning",
              duration: 2500,
            });
          }
          return item.costId && item.bindNum;
        });
        if (float) {
          let hisItemList = this.tableList.map((item) => {
            return {
              costId: item.costId,
              bindNum: item.bindNum,
            };
          });
          bindCost({
            treatmentId: this.treatmentId,
            hisItemList,
          })
            .then((res) => {
              this.getList();
              this.$notify({
                title: "保存成功",
                type: "success",
                duration: 2500,
              });
            })
            .catch((res) => {
              this.$notify({
                title: res.msg,
                type: "error",
                duration: 2500,
              });
            });
        }
      }
    },
    //新增
    addSingle() {
      let time = moment().format("x");
      this.tableList.push({
        id: time,
        index: this.tableList.length + 1,
        bindNum: 1,
      });
    },
    //删除
    delSingle() {
      let list = [];
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        console.log(this.selectedRowKeys);
        let idArray = this.selectedRowKeys.map((item) => {
          if (!item.id) {
            list.push(item);
          }
          return item.index;
        });
        this.tableList = this.tableList.filter((item, index) => {
          if (item.costId) {
            if (list && list.length > 0 && index == list.length - 1) {
              unBind({
                treatmentId: this.treatmentId,
                hisItemList: list.map((lItem) => {
                  return {
                    costId: lItem.costId,
                  };
                }),
              })
                .then((res) => {
                  // this.getList();
                  this.$notify({
                    title: "删除成功",
                    type: "success",
                    duration: 2500,
                  });
                })
                .catch((res) => {
                  // this.getList();
                  // this.$notify({
                  //   title: res.msg,
                  //   type: "error",
                  //   duration: 2500,
                  // });
                });
            }
          }
          return !idArray.includes(item.index);
        });
      } else {
        this.$notify({
          title: "请选择费用",
          type: "warning",
          duration: 2500,
        });
      }
    },
    selectionChangeHandler(val) {
      this.selectedRowKeys = val;
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.crud-opts {
  display: inline-flex;
}

.table_title {
  display: inline-block;
  line-height: 30px;
  margin: 0 10px 0 0;
  vertical-align: middle;
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.head-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 0;
  /deep/.filter-item {
    margin-bottom: 0;
  }
}
</style>
